package base.thread_JUC.demo06;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多线程之间按顺序调用，实现A -> B -> C三个线程启动，要求如下：
 * AA打印5次，BB打印10次，CC打印15次
 * 紧接着
 * AA打印5次，BB打印10次，CC打印15次
 * ....
 * 来10轮
 */
public class SyncAndReentrantLockDemo {
    public static void main(String[] args) {
        ShareSource share = new ShareSource();

        new Thread(()->{
            share.print5();
        },"AA").start();

        new Thread(()->{
            share.print10();
        },"BB").start();

        new Thread(()->{
            share.print15();
        },"CC").start();

    }
}

class ShareSource {
    Integer number = 1;//A:1, B:2, C:3
    Lock lock = new ReentrantLock(false);//默认就是非公平锁
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    public void print5(){
        for (int i = 1; i <=10 ; i++) {
            try {
                lock.lock();
                while (number != 1){
                    System.out.println(Thread.currentThread().getName()+"\t 进入 await, 并释放 c1 关联的 lock ");
                    c1.await();
                }
                for (int j = 1; j <= 5; j++) {
                    System.out.println(Thread.currentThread().getName()+"\t"+j);
                }
                number = 2;
                c2.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    public void print10(){
        for (int i = 1; i <=10 ; i++) {
            try {
                lock.lock();
                while (number != 2){
                    System.out.println(Thread.currentThread().getName()+"\t 进入 await, 并释放 c2 关联的 lock ");
                    c2.await();
                }
                for (int j = 1; j <= 10; j++) {
                    System.out.println(Thread.currentThread().getName()+"\t"+j);
                }
                number = 3;
                c3.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    public void print15(){
        for (int i = 1; i <=10 ; i++) {
            try {
                lock.lock();
                while (number != 3){
                    System.out.println(Thread.currentThread().getName()+"\t 进入 await, 并释放 c3 关联的 lock ");
                    c3.await();
                }
                for (int j = 1; j <= 15; j++) {
                    System.out.println(Thread.currentThread().getName()+"\t"+j);
                }
                number = 1;
                c1.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }


}
